<?php
/**
 * 新建违规记录页面
 * 功能：添加新的违规记录并更新风险指数
 * 权限：仅考试项目管理员可访问
 */

// 开启输出缓冲以解决header重定向问题
ob_start();

// 开启会话
session_start();

// 错误报告设置
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    ob_end_clean();
    header('Location: index.php');
    exit();
}

// 为navigation.php设置必需变量
$current_user_id = $_SESSION['user_id'] ?? '';
$GLOBALS['current_user_id'] = $current_user_id;

// 数据库连接
try {
    if (!file_exists('database.php')) {
        throw new Exception("database.php文件不存在");
    }

    require_once 'database.php';

    if (!isset($conn) || !($conn instanceof mysqli)) {
        throw new Exception("数据库连接失败");
    }

    if (!$conn->ping()) {
        throw new Exception("数据库连接已断开");
    }

} catch (Exception $e) {
    $_SESSION['error_message'] = "数据库连接失败：" . $e->getMessage();
    ob_end_clean();
    header('Location: user_home.php');
    exit();
}

// 包含统一导航栏 - 必须在使用getUserRoles之前包含
if (file_exists('common/navigation.php')) {
    require_once 'common/navigation.php';
}

// 权限验证 - 现在getUserRoles函数已经通过navigation.php定义
$user_roles = getUserRoles($current_user_id);
if (!in_array('考试项目管理员', $user_roles)) {
    $_SESSION['error_message'] = "访问被拒绝：您需要考试项目管理员权限才能访问此页面";
    ob_end_clean();
    header('Location: access_denied.php');
    exit();
}

// 获取考试项目ID
$exam_id = intval($_GET['exam_id'] ?? 0);
if ($exam_id <= 0) {
    $_SESSION['error_message'] = "无效的考试项目ID";
    ob_end_clean();
    header('Location: exam_projects.php');
    exit();
}

// 风险指数计算函数
function calculateRiskIndex($user_id, $conn) {
    try {
        // 获取该用户的所有违规记录
        $violations_sql = "SELECT severity_level FROM violations WHERE invigilator_id = ?";
        $violations_stmt = $conn->prepare($violations_sql);
        $violations_stmt->bind_param("s", $user_id);
        $violations_stmt->execute();
        $violations_result = $violations_stmt->get_result();

        $base_risk = 1.00; // 基础风险指数
        $risk_increment = 0;

        // 根据违规严重程度增加风险指数
        while ($row = $violations_result->fetch_assoc()) {
            switch ($row['severity_level']) {
                case '轻微':
                    $risk_increment += 0.1;
                    break;
                case '一般':
                    $risk_increment += 0.3;
                    break;
                case '严重':
                    $risk_increment += 0.5;
                    break;
                case '极严重':
                    $risk_increment += 1.0;
                    break;
            }
        }

        $violations_stmt->close();

        $new_risk_index = $base_risk + $risk_increment;

        // 更新staff表中的risk_index
        $update_sql = "UPDATE staff SET risk_index = ? WHERE user_id = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("ds", $new_risk_index, $user_id);
        $update_stmt->execute();
        $update_stmt->close();

        return $new_risk_index;

    } catch (Exception $e) {
        error_log("计算风险指数失败: " . $e->getMessage());
        return 1.00;
    }
}

// 处理表单提交 - 在任何输出之前处理
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $selected_exam_id = intval($_POST['exam_id'] ?? 0);
        $exam_session = trim($_POST['exam_session'] ?? '');
        $invigilator_id = trim($_POST['invigilator_id'] ?? '');
        $violation_date = trim($_POST['violation_date'] ?? '');
        $violation_type = trim($_POST['violation_type'] ?? '');
        $severity_level = trim($_POST['severity_level'] ?? '');
        $description = trim($_POST['description'] ?? '');

        // 表单验证
        if ($selected_exam_id <= 0) {
            throw new Exception("请选择考试项目");
        }
        if (empty($invigilator_id)) {
            throw new Exception("请选择监考员");
        }
        if (empty($violation_date)) {
            throw new Exception("请选择违规日期");
        }
        if (empty($violation_type)) {
            throw new Exception("请输入违规类型");
        }
        if (empty($severity_level)) {
            throw new Exception("请选择严重程度");
        }

        // 获取考试项目名称和监考员姓名
        $exam_info_sql = "SELECT exam_name FROM exams WHERE id = ?";
        $exam_info_stmt = $conn->prepare($exam_info_sql);
        $exam_info_stmt->bind_param("i", $selected_exam_id);
        $exam_info_stmt->execute();
        $exam_info_result = $exam_info_stmt->get_result();
        $exam_info = $exam_info_result->fetch_assoc();
        $exam_info_stmt->close();

        $staff_info_sql = "SELECT name FROM staff WHERE user_id = ?";
        $staff_info_stmt = $conn->prepare($staff_info_sql);
        $staff_info_stmt->bind_param("s", $invigilator_id);
        $staff_info_stmt->execute();
        $staff_info_result = $staff_info_stmt->get_result();
        $staff_info = $staff_info_result->fetch_assoc();
        $staff_info_stmt->close();

        if (!$exam_info || !$staff_info) {
            throw new Exception("考试项目或监考员信息不存在");
        }

        // 计算违反纪律积分
        $disciplinary_points = 0.0;
        switch ($severity_level) {
            case '轻微':
                $disciplinary_points = 0.1;
                break;
            case '一般':
                $disciplinary_points = 0.3;
                break;
            case '严重':
                $disciplinary_points = 0.5;
                break;
            case '极严重':
                $disciplinary_points = 1.0;
                break;
        }

        // 插入违规记录（包含违反纪律积分）
        $insert_sql = "INSERT INTO violations (exam_id, exam_name, exam_session, invigilator_name, invigilator_id, violation_date, violation_type, severity_level, description, disciplinary_violation_points, reported_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $insert_stmt = $conn->prepare($insert_sql);

        if (!$insert_stmt) {
            throw new Exception("准备插入语句失败: " . $conn->error);
        }

        $insert_stmt->bind_param("issssssssds",
            $selected_exam_id,
            $exam_info['exam_name'],
            $exam_session,
            $staff_info['name'],
            $invigilator_id,
            $violation_date,
            $violation_type,
            $severity_level,
            $description,
            $disciplinary_points,
            $current_user_id
        );

        if ($insert_stmt->execute()) {
            $success_message = "违规记录添加成功！违反纪律积分值为 " . number_format($disciplinary_points, 1);
            $_SESSION['success_message'] = $success_message;

            // 关闭数据库连接
            $insert_stmt->close();
            if (isset($conn) && $conn instanceof mysqli) {
                $conn->close();
            }

            // 清空输出缓冲区并重定向到违规记录展示页面
            ob_end_clean();
            header("Location: violations_display.php?exam_id=" . $selected_exam_id);
            exit();
        } else {
            throw new Exception("插入违规记录失败: " . $insert_stmt->error);
        }

        $insert_stmt->close();

    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// 初始化变量
$exam = null;
$staff_list = [];
$exams_list = [];
if (!isset($error_message)) {
    $error_message = '';
}
$success_message = '';

// 获取考试项目信息
try {
    $exam_sql = "SELECT * FROM exams WHERE id = ? AND status = 'active'";
    $exam_stmt = $conn->prepare($exam_sql);

    if (!$exam_stmt) {
        throw new Exception("准备查询语句失败: " . $conn->error);
    }

    $exam_stmt->bind_param("i", $exam_id);
    $exam_stmt->execute();
    $result = $exam_stmt->get_result();

    if ($result->num_rows === 0) {
        throw new Exception("考试项目不存在或已被删除");
    }

    $exam = $result->fetch_assoc();
    $exam_stmt->close();

} catch (Exception $e) {
    $error_message = $e->getMessage();
    $_SESSION['error_message'] = $error_message;
    ob_end_clean();
    header('Location: exam_projects.php');
    exit();
}

// 获取所有考试项目列表
try {
    $exams_sql = "SELECT id, exam_name FROM exams WHERE status = 'active' ORDER BY exam_name";
    $exams_result = $conn->query($exams_sql);

    if ($exams_result) {
        while ($row = $exams_result->fetch_assoc()) {
            $exams_list[] = $row;
        }
    }
} catch (Exception $e) {
    error_log("获取考试项目列表失败: " . $e->getMessage());
}

// 获取员工列表（监考员）
try {
    $staff_sql = "SELECT user_id, name FROM staff WHERE serving = 1 ORDER BY user_id ASC";
    $staff_result = $conn->query($staff_sql);

    if ($staff_result) {
        while ($row = $staff_result->fetch_assoc()) {
            $staff_list[] = $row;
        }
    }
} catch (Exception $e) {
    error_log("获取员工列表失败: " . $e->getMessage());
}

$page_title = '新建违规记录 - 考务管理系统';
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

    <style>
        .main-content {
            margin-top: 20px;
            padding-bottom: 40px;
        }

        .page-header {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            text-align: center;
        }

        .info-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 25px;
            margin-bottom: 30px;
        }

        .form-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 30px;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .form-section h5 {
            color: #495057;
            border-bottom: 2px solid #e9ecef;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }

        .form-label {
            font-weight: 600;
            color: #495057;
        }

        .form-control:focus, .form-select:focus {
            border-color: #dc3545;
            box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc3545, #c82333);
            border: none;
            padding: 12px 30px;
            font-weight: 600;
        }

        .btn-danger:hover {
            background: linear-gradient(135deg, #c82333, #bd2130);
            transform: translateY(-1px);
        }

        .btn-secondary {
            padding: 12px 30px;
            font-weight: 600;
        }

        .severity-info {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 10px;
        }

        .severity-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
        }

        .severity-item:last-child {
            margin-bottom: 0;
        }

        .severity-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: 600;
            margin-right: 10px;
            min-width: 60px;
            text-align: center;
        }

        .severity-轻微 { background-color: #d1ecf1; color: #0c5460; }
        .severity-一般 { background-color: #fff3cd; color: #856404; }
        .severity-严重 { background-color: #f8d7da; color: #721c24; }
        .severity-极严重 { background-color: #dc3545; color: white; }

        .required {
            color: #dc3545;
        }
    </style>
</head>
<body>
<!-- 导航栏已通过navigation.php包含并渲染 -->

<!-- 主要内容 -->
<div class="container main-content">
    <!-- 页面标题 -->
    <div class="page-header">
        <h1 class="mb-2">
            <i class="fas fa-plus-circle"></i> 新建违规记录
        </h1>
        <p class="mb-0">添加新的监考员违规记录</p>
    </div>

    <!-- 考试项目信息 -->
    <div class="info-card">
        <h5 class="mb-3"><i class="fas fa-info-circle text-info"></i> 当前考试项目信息</h5>
        <h4 class="text-primary"><?php echo htmlspecialchars($exam['exam_name']); ?></h4>
        <div class="row mt-3">
            <div class="col-md-6">
                <p><strong>考试日期：</strong><?php echo htmlspecialchars($exam['exam_date']); ?></p>
                <p><strong>结束日期：</strong><?php echo htmlspecialchars($exam['end_date'] ?? '未设置'); ?></p>
            </div>
            <div class="col-md-6">
                <p><strong>科目数量：</strong><?php echo intval($exam['subject_count']); ?> 门</p>
                <p><strong>创建者：</strong><?php echo htmlspecialchars($exam['created_by']); ?></p>
            </div>
        </div>
    </div>

    <!-- 成功消息 -->
    <?php if (!empty($success_message)): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- 错误消息 -->
    <?php if (!empty($error_message)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- 违规记录表单 -->
    <div class="form-container">
        <form method="POST" id="violationForm">
            <!-- 基本信息 -->
            <div class="form-section">
                <h5><i class="fas fa-clipboard"></i> 基本信息</h5>
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="exam_id" class="form-label">考试项目 <span class="required">*</span></label>
                            <select class="form-select" id="exam_id" name="exam_id" required>
                                <option value="">请选择考试项目</option>
                                <?php foreach ($exams_list as $exam_option): ?>
                                    <option value="<?php echo $exam_option['id']; ?>" <?php echo ($exam_option['id'] == $exam_id) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($exam_option['exam_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="exam_session" class="form-label">考试场次 <span class="required">*</span></label>
                            <select class="form-select" id="exam_session" name="exam_session" required>
                                <option value="">请先选择考试项目</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="invigilator_id" class="form-label">监考员 <span class="required">*</span></label>
                            <select class="form-select" id="invigilator_id" name="invigilator_id" required>
                                <option value="">请选择监考员</option>
                                <?php foreach ($staff_list as $staff): ?>
                                    <option value="<?php echo htmlspecialchars($staff['user_id']); ?>">
                                        <?php echo htmlspecialchars($staff['name']); ?> (<?php echo htmlspecialchars($staff['user_id']); ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="violation_date" class="form-label">违规日期 <span class="required">*</span></label>
                            <input type="date" class="form-control" id="violation_date" name="violation_date"
                                   value="<?php echo htmlspecialchars($exam['exam_date']); ?>" required>
                            <div class="form-text" id="date-range-info">请先选择考试项目以确定日期范围</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 违规详情 -->
            <div class="form-section">
                <h5><i class="fas fa-exclamation-triangle"></i> 违规详情</h5>
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="violation_type" class="form-label">违规类型 <span class="required">*</span></label>
                            <select class="form-select" id="violation_type" name="violation_type" required>
                                <option value="">请选择违规类型</option>
                                <option value="迟到早退">迟到早退</option>
                                <option value="擅离职守">擅离职守</option>
                                <option value="通讯设备违规">通讯设备违规</option>
                                <option value="监考失职">监考失职</option>
                                <option value="行为不当">行为不当</option>
                                <option value="程序违规">程序违规</option>
                                <option value="包庇作弊">包庇作弊</option>
                                <option value="信息泄露">信息泄露</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="severity_level" class="form-label">严重程度 <span class="required">*</span></label>
                            <select class="form-select" id="severity_level" name="severity_level" required>
                                <option value="">请选择严重程度</option>
                                <option value="轻微">轻微</option>
                                <option value="一般">一般</option>
                                <option value="严重">严重</option>
                                <option value="极严重">极严重</option>
                            </select>
                            <div class="severity-info">
                                <div class="severity-item">
                                    <span class="severity-badge severity-轻微">轻微</span>
                                    <span>风险指数 +0.1</span>
                                </div>
                                <div class="severity-item">
                                    <span class="severity-badge severity-一般">一般</span>
                                    <span>风险指数 +0.3</span>
                                </div>
                                <div class="severity-item">
                                    <span class="severity-badge severity-严重">严重</span>
                                    <span>风险指数 +0.5</span>
                                </div>
                                <div class="severity-item">
                                    <span class="severity-badge severity-极严重">极严重</span>
                                    <span>风险指数 +1.0</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="description" class="form-label">违规描述 <span class="required">*</span></label>
                    <textarea class="form-control" id="description" name="description" rows="4"
                              placeholder="请详细描述违规情况..." required></textarea>
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="d-flex justify-content-between">
                <a href="violations_display.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> 返回列表
                </a>
                <div>
                    <button type="button" class="btn btn-outline-secondary me-2" onclick="resetForm()">
                        <i class="fas fa-undo"></i> 重置
                    </button>
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-save"></i> 确认违规记录
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
    // 违规类型和描述的映射关系
    const violationDescriptions = {
        '迟到早退': '监考员未按规定时间到达考场/提前离开监考岗位',
        '擅离职守': '监考期间无故离开考场/长时间不在监考岗位',
        '通讯设备违规': '监考期间使用手机等电子设备/未按要求存放通讯工具',
        '监考失职': '未核对考生身份信息/未发现或未制止作弊行为/未按要求分发/回收试卷',
        '行为不当': '在考场内睡觉/阅读无关书籍/与考生进行非必要交流/在考场内吸烟/饮食',
        '程序违规': '提前拆封试卷/擅自延长/缩短考试时间/未按要求填写考场记录',
        '包庇作弊': '协助考生作弊/故意隐瞒作弊行为',
        '信息泄露': '提前泄露考试内容/违规拍摄/传播试卷'
    };

    // 考试项目改变时的处理函数
    function handleExamChange() {
        const examSelect = document.getElementById('exam_id');
        const sessionSelect = document.getElementById('exam_session');
        const dateInput = document.getElementById('violation_date');
        const dateInfo = document.getElementById('date-range-info');

        const examId = examSelect.value;

        if (!examId) {
            sessionSelect.innerHTML = '<option value="">请先选择考试项目</option>';
            dateInput.removeAttribute('min');
            dateInput.removeAttribute('max');
            dateInfo.textContent = '请先选择考试项目以确定日期范围';
            return;
        }

        // 获取考试项目信息
        fetch(`get_exam_info.php?exam_id=${examId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新考试场次选项
                    sessionSelect.innerHTML = '<option value="">请选择考试场次</option>';
                    for (let i = 1; i <= data.subject_count; i++) {
                        sessionSelect.innerHTML += `<option value="${i}">第${i}场次</option>`;
                    }

                    // 更新日期范围
                    if (data.exam_date) {
                        dateInput.setAttribute('min', data.exam_date);
                        let maxDate = data.end_date || data.exam_date;
                        dateInput.setAttribute('max', maxDate);
                        dateInfo.textContent = `违规日期范围：${data.exam_date} 至 ${maxDate}`;
                    }
                } else {
                    sessionSelect.innerHTML = '<option value="">获取场次信息失败</option>';
                    dateInfo.textContent = '获取日期范围失败';
                }
            })
            .catch(error => {
                console.error('获取考试信息失败:', error);
                sessionSelect.innerHTML = '<option value="">获取场次信息失败</option>';
                dateInfo.textContent = '获取日期范围失败';
            });
    }

    // 违规类型改变时的处理函数
    function handleViolationTypeChange() {
        const typeSelect = document.getElementById('violation_type');
        const descriptionTextarea = document.getElementById('description');

        const selectedType = typeSelect.value;

        if (selectedType && violationDescriptions[selectedType]) {
            descriptionTextarea.value = violationDescriptions[selectedType];
        } else {
            descriptionTextarea.value = '';
        }
    }

    // 绑定事件监听器
    document.getElementById('exam_id').addEventListener('change', handleExamChange);
    document.getElementById('violation_type').addEventListener('change', handleViolationTypeChange);

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 如果页面加载时已经选择了考试项目，则触发更新
        if (document.getElementById('exam_id').value) {
            handleExamChange();
        }
    });

    // 重置表单
    function resetForm() {
        if (confirm('确定要重置表单吗？所有输入的信息将丢失。')) {
            document.getElementById('violationForm').reset();
            // 重置后重新初始化
            handleExamChange();
        }
    }

    // 表单验证
    document.getElementById('violationForm').addEventListener('submit', function(e) {
        const examId = document.getElementById('exam_id').value;
        const examSession = document.getElementById('exam_session').value;
        const invigilatorId = document.getElementById('invigilator_id').value;
        const violationDate = document.getElementById('violation_date').value;
        const violationType = document.getElementById('violation_type').value;
        const severityLevel = document.getElementById('severity_level').value;
        const description = document.getElementById('description').value.trim();

        if (!examId) {
            alert('请选择考试项目');
            e.preventDefault();
            return;
        }

        if (!examSession) {
            alert('请选择考试场次');
            e.preventDefault();
            return;
        }

        if (!invigilatorId) {
            alert('请选择监考员');
            e.preventDefault();
            return;
        }

        if (!violationDate) {
            alert('请选择违规日期');
            e.preventDefault();
            return;
        }

        if (!violationType) {
            alert('请选择违规类型');
            e.preventDefault();
            return;
        }

        if (!severityLevel) {
            alert('请选择严重程度');
            e.preventDefault();
            return;
        }

        if (!description) {
            alert('请填写违规描述');
            e.preventDefault();
            return;
        }

        // 确认提交
        if (!confirm('确定要添加这条违规记录吗？\n\n这将会影响该监考员的风险指数。')) {
            e.preventDefault();
        }
    });
</script>

<?php
// 关闭数据库连接
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>
</body>
</html>